﻿using Uiap.Infrastructure.Runtime.Caching;
using System;
using System.Threading.Tasks;

namespace Uiap.Infrastructure.Idempotency
{
    /// <summary>
    /// 请求管理器
    /// </summary>
    public class RequestManager : IRequestManager
    {
        private readonly ICacheManager _cacheManager;

        public RequestManager(ICacheManager cacheManager)
        {
            _cacheManager = cacheManager ?? throw new ArgumentNullException(nameof(cacheManager));
        }

        public async Task<bool> ExistAsync(Guid id)
        {
            var request = _cacheManager.IsSet($"idempotency.{id}");

            return await Task.FromResult(request);
        }

        public async Task CreateRequestForCommandAsync<T>(Guid id)
        { 
            var exists = await ExistAsync(id);

            var request = exists ? 
                throw new Exception($"Request with {id} already exists") : 
                new ClientRequest()
                {
                    Id = id,
                    Name = typeof(T).Name,
                    Time = DateTime.UtcNow
                };

            ///缓存一天
            _cacheManager.Set($"idempotency.{id}", request, 24 * 60 * 60);            
        }
    }
}
